
//
//  Knob.h
//  SKPAD
//
//  Created by admin@amonline.com.cn on 15/5/8.
//  Copyright (c) 2015年 何睿 All rights reserved.
//

#import "Knob.h"


@implementation Knob

//代码创建初始化
-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        _trackLayerKnob = [CALayer layer];
        _trackLayerKnob.backgroundColor = [UIColor clearColor].CGColor;
        _knobView = (id)[UIImage imageNamed:@"encoder.png"].CGImage;
        _trackLayerKnob.bounds = frame;
        _trackLayerKnob.contents =_knobView;
    }
    return  self;
}

-(void)updateWithPosition:(CGRect)bounds
{
    //设置图层中心位置
    self.trackLayerKnob.position = CGPointMake(CGRectGetWidth(bounds)/2.0, CGRectGetHeight(bounds)/2.0);
}

-(void) setStartAngle:(CGFloat)startAngle
{
    if(startAngle != _startAngle)
    {
        _startAngle = startAngle;
    }
}

-(void) setEndAngle:(CGFloat)endAngle
{
    if(endAngle != _endAngle)
    {
        _endAngle = endAngle;
    }
}

-(void) setKnobPointerAngle:(CGFloat)knobPointerAngle
{
    //124行阻止隐士动画，值改变knob会立即响应；
    //[CATransaction new];
    //[CATransaction setDisableActions:YES];
    //_trackLayerKnob.transform = CATransform3DMakeRotation(knobPointerAngle, 0, 0, 1);
    //[CATransaction commit];
    [self setKnobPointerAngle:knobPointerAngle animated:YES];
}

-(void) setKnobPointerAngle:(CGFloat)knobPointerAngle animated:(BOOL)animated
{
    [CATransaction new];
    [CATransaction setDisableActions:YES];
    _trackLayerKnob.transform = CATransform3DMakeRotation(knobPointerAngle, 0, 0, 1);
    if(animated)
    {
        //设置当前值和新值的中间值
        CGFloat midAngle = (MAX(knobPointerAngle, _knobPointerAngle) - MIN(knobPointerAngle, _knobPointerAngle) / 2.f + MIN(knobPointerAngle, _knobPointerAngle));
        //设置动画方式，用到CAKey关键帧，使动画在旋转的时候不会选择角度小的一边旋转
        CAKeyframeAnimation * animationKey = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"];
        animationKey.duration = 0.25f;
        animationKey.values = @[@(_knobPointerAngle), @(midAngle), @(knobPointerAngle)];
        animationKey.keyTimes = @[@(0), @(0.5), @(1.0)];
        animationKey.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [self.trackLayerKnob addAnimation:animationKey forKey:nil];
    }
    [CATransaction commit];
    _knobPointerAngle = knobPointerAngle;
}
@end